package com.tsingtree.sys.modular.system.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tsingtree.base.auth.context.LoginContextHolder;
import com.tsingtree.base.auth.model.LoginUser;
import com.tsingtree.base.consts.ConstantsContext;
import com.tsingtree.base.pojo.node.MenuNode;
import com.tsingtree.base.pojo.page.LayuiPageFactory;
import com.tsingtree.roses.kernel.model.exception.ServiceException;
import com.tsingtree.sys.core.constant.Const;
import com.tsingtree.sys.core.constant.factory.ConstantFactory;
import com.tsingtree.sys.core.constant.state.ManagerStatus;
import com.tsingtree.sys.core.exception.enums.BizExceptionEnum;
import com.tsingtree.sys.core.util.SaltUtil;
import com.tsingtree.sys.modular.system.entity.SysUser;
import com.tsingtree.sys.modular.system.factory.UserFactory;
import com.tsingtree.sys.modular.system.mapper.SysUserMapper;
import com.tsingtree.sys.modular.system.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author  jagger
 * @since 2018-12-07
 */
@Service
public class SysUserService extends ServiceImpl<SysUserMapper, SysUser> {

    @Autowired
    private MenuService menuService;

    /**
     * 添加用戶
     *
     * @author jagger
     */
    @Transactional(rollbackFor = Exception.class)
    public void addUser(UserDto user) {

        // 判断账号是否重复
        SysUser theUser = this.getByAccount(user.getAccount());
        if (theUser != null) {
            throw new ServiceException(BizExceptionEnum.USER_ALREADY_REG);
        }

        // 完善账号信息
        String salt = SaltUtil.getRandomSalt();
        String password = SaltUtil.md5Encrypt(user.getPassword(), salt);

        SysUser newUser = UserFactory.createUser(user, password, salt);
        this.save(newUser);

    }

    /**
     * 修改用户
     *
     * @author jagger
     */
    @Transactional(rollbackFor = Exception.class)
    public void editUser(UserDto user) {
        SysUser oldUser = this.getById(user.getUserId());

        if (LoginContextHolder.getContext().hasRole(Const.ADMIN_NAME)) {
            this.updateById(UserFactory.editUser(user, oldUser));
        } else {
            LoginUser shiroUser = LoginContextHolder.getContext().getUser();
            if (shiroUser.getId().equals(user.getUserId())) {
                this.updateById(UserFactory.editUser(user, oldUser));
            } else {
                throw new ServiceException(BizExceptionEnum.NO_PERMITION);
            }
        }

    }

    /**
     * 删除用户
     *
     * @author jagger
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Long userId) {

        //不能删除超级管理员
        if (userId.equals(Const.ADMIN_ID)) {
            throw new ServiceException(BizExceptionEnum.CANT_DELETE_ADMIN);
        }
        this.setStatus(userId, ManagerStatus.DELETED.getCode());

        //删除对应的oauth2绑定表
//        SqlRunner.db().delete("delete from oauth_user_info where user_id = {0}", userId);

    }

    /**
     * 修改用户状态
     *
     * @author jagger
     */
    public int setStatus(Long userId, String status) {
        return this.baseMapper.setStatus(userId, status);
    }

    /**
     * 修改密码
     *
     * @author jagger
     */
    public void changePwd(String oldPassword, String newPassword) {
        Long userId = LoginContextHolder.getContext().getUser().getId();
        SysUser user = this.getById(userId);

        String oldMd5 = SaltUtil.md5Encrypt(oldPassword, user.getSalt());

        if (user.getPassword().equals(oldMd5)) {
            String newMd5 = SaltUtil.md5Encrypt(newPassword, user.getSalt());
            user.setPassword(newMd5);
            this.updateById(user);
        } else {
            throw new ServiceException(BizExceptionEnum.OLD_PWD_NOT_RIGHT);
        }
    }

    /**
     * 根据条件查询用户列表
     *
     * @author jagger
     */
    public Page<Map<String, Object>> selectUsers(String name, String beginTime, String endTime) {
        Page page = LayuiPageFactory.defaultPage();
        return this.baseMapper.selectUsers(page, name, beginTime, endTime);
    }

    /**
     * 设置用户的角色
     *
     * @author jagger
     */
    public int setRoles(Long userId, String roleIds) {
        return this.baseMapper.setRoles(userId, roleIds);
    }

    /**
     * 通过账号获取用户
     *
     * @author jagger
     */
    public SysUser getByAccount(String account) {
        return this.baseMapper.getByAccount(account);
    }

    /**
     * 获取用户菜单列表
     *
     * @author jagger
     */
    public List<Map<String, Object>> getUserMenuNodes(List<Long> roleList) {
        if (roleList == null || roleList.size() == 0) {
            return new ArrayList<>();
        } else {
            List<MenuNode> menus = menuService.getMenusByRoleIds(roleList);

            //定义不同系统分类的菜单集合
            ArrayList<Map<String, Object>> lists = new ArrayList<>();
            HashMap<String, Object> map = new HashMap<>();
            List<MenuNode> treeSystemTypeMenus = MenuNode.buildTitle(menus);
            map.put("systemType", "SYSTEM_TYPE");
            map.put("menus", treeSystemTypeMenus);
            lists.add(map);
            return lists;
        }
    }

    /**
     * 刷新当前登录用户的信息
     *
     * @author jagger
     */
    public void refreshCurrentUser() {
        //TODO 刷新
    }

    /**
     * 获取用户的基本信息
     *
     * @author jagger
     */
    public Map<String, Object> getUserInfo(Long userId) {
        SysUser user = this.getById(userId);
        Map<String, Object> map = UserFactory.removeUnSafeFields(user);

        HashMap<String, Object> hashMap = new HashMap<>(map);
        hashMap.put("roleName", ConstantFactory.me().getRoleName(user.getRoleId()));

        return hashMap;
    }

    /**
     * 获取用户首页信息
     *
     * @author jagger
     */
    public Map<String, Object> getUserIndexInfo() {

        //获取当前用户角色列表
        LoginUser user = LoginContextHolder.getContext().getUser();
        List<Long> roleList = user.getRoleList();

        //用户没有角色无法显示首页信息
        if (roleList == null || roleList.size() == 0) {
            return null;
        }

        List<Map<String, Object>> menus = this.getUserMenuNodes(roleList);

        HashMap<String, Object> result = new HashMap<>();
        result.put("menus", menus);
        result.put("avatar", ConstantsContext.getCdn() +user.getAvatar());
        result.put("name", user.getName());

        return result;
    }


    /**
     * 选择办理人
     *
     * @author jagger
     */
    public IPage listUserAndRoleExpectAdmin(Page pageContext) {
        return baseMapper.listUserAndRoleExpectAdmin(pageContext);
    }
}
